package io.geekidea.boot.system.controller;

import com.google.common.base.Joiner;
import com.hwtx.form.controller.Api2Result;
import com.hwtx.form.domain.def.ResourceTreeOption;
import com.hwtx.form.domain.repo.SysUserRepo;
import com.hwtx.form.domain.service.RacService;
import com.hwtx.form.domain.service.ResourceService;
import com.hwtx.form.dto.RoleDataResourceDto;
import io.geekidea.boot.auth.util.LoginUtil;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.response.ApiCode;
import io.geekidea.boot.framework.response.ApiResult;
import io.geekidea.boot.system.dto.*;
import io.geekidea.boot.system.query.SysMenuQuery;
import io.geekidea.boot.system.query.SysUserQuery;
import io.geekidea.boot.system.vo.AmisTableData;
import io.geekidea.boot.system.vo.SysUserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Set;

/**
 * 系统用户 控制器
 *
 * @author geekidea
 * @since 2022-12-26
 */
@Slf4j
@RestController
@Tag(name = "系统用户")
@RequestMapping("/admin/sysUser")
public class SysUserController {

    @Resource
    private SysUserRepo sysUserRepo;
    @Resource
    private ResourceService resourceService;
    @Resource
    private RacService racService;

    @PostMapping("/quickUpdate")
    @Operation(summary = "快速更新系统用户")
    public Api2Result updateSysUser(@Valid @RequestBody QuickDto quickDto) {
        List<UserDto> list = QuickDto.convert(quickDto.getRowsDiff(), UserDto.class);
        list.forEach(sysUser -> sysUserRepo.updateSysUser(sysUser));
        return Api2Result.result(ApiCode.SUCCESS, "修改成功", true);
    }

    @PostMapping("/updateUser")
    @Operation(summary = "更新系统用户")
    public Api2Result updateUser(@RequestBody UserDto userDto) {
        return Api2Result.result(ApiCode.SUCCESS, "更新成功", sysUserRepo.updateSysUser(userDto) > 0);
    }

    @PostMapping("/updateUsers")
    @Operation(summary = "批量更新系统用户")
    public Api2Result updateUsers(@RequestBody BulkUserDto userDto) {
        return Api2Result.result(ApiCode.SUCCESS, "更新成功", sysUserRepo.updateSysUsers(userDto));
    }

    /**
     * 删除系统用户
     */
    @PostMapping("/deleteSysUser/{id}")
    @Operation(summary = "删除系统用户")
    public ApiResult deleteSysUser(@PathVariable Long id) {
        boolean flag = sysUserRepo.deleteSysUser(id);
        return ApiResult.result(flag);
    }

    /**
     * 获取系统用户详情
     */
    @PostMapping("/getSysUser/{id}")
    @Operation(summary = "系统用户详情")
    public Api2Result getSysUser(@PathVariable Long id) {
        return Api2Result.success(sysUserRepo.getSysUserById(id));
    }

    /**
     * 系统用户分页列表
     */
    @RequestMapping("/getSysUserPage")
    @Operation(summary = "系统用户分页列表")
    public Api2Result getSysUserPage(@Valid @RequestBody SysUserQuery query) {
        return Api2Result.success(sysUserRepo.getSysUserPage(query));
    }

    @GetMapping("/allRoleDataRes")
    @Operation(summary = "获取用户已赋予的角色数据权限")
    @Deprecated
    public Api2Result getAllRes(@RequestParam Long userId) {
        List<RoleDataResourceDto> list = racService.getRoleDataResourceByUser(userId);
        AmisTableData<RoleDataResourceDto> misTableData = new AmisTableData<>();
        misTableData.setRows(list);
        return Api2Result.success(misTableData);
    }

    @GetMapping("/allRes")
    @Operation(summary = "获取用户已赋予的资源")
    public Api2Result getAllDataRes(@RequestParam Long userId) {
        List<ResourceTreeOption> list = resourceService.getResourceForRoleTree(new SysMenuQuery());
        Set<Long> resources = racService.getUserResources(userId);
        AmisTableData<ResourceTreeOption> misTableData = new AmisTableData<>();
        misTableData.setRows(list);
        misTableData.setValue(Joiner.on(',').join(resources));
        return Api2Result.success(misTableData);
    }

    /**
     * 重置系统用户密码
     */
    @PostMapping("/resetPwd")
    @Operation(summary = "重置系统用户密码")
    public Api2Result resetSysUserPassword(@Valid @RequestBody SysUserResetPasswordDto sysUserResetPasswordDto) {
        boolean flag = sysUserRepo.resetSysUserPassword(sysUserResetPasswordDto);
        return Api2Result.result(flag);
    }

    /**
     * 获取个人信息
     */
    @PostMapping("/getProfile")
    @Operation(summary = "获取个人信息")
    public ApiResult<SysUserVo> getProfile() {
        Long userId = LoginUtil.getUserId();
        if (userId == null) {
            throw new BusinessException("用户ID为空");
        }
        SysUserVo sysUserVo = sysUserRepo.getSysUserById(userId);
        return ApiResult.success(sysUserVo);
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/updateProfile")
    @Operation(summary = "修改个人信息")
    public ApiResult updateProfile(@Valid @RequestBody SysUserUpdateProfileDto sysUserUpdateProfileDto) {
        boolean flag = sysUserRepo.updateProfile(sysUserUpdateProfileDto);
        return ApiResult.result(flag);
    }

    /**
     * 导入Excel用户数据
     */
    @PostMapping("/importExcel")
    @Operation(summary = "导入Excel用户数据")
    public ApiResult importExcel(MultipartFile multipartFile) throws Exception {
        boolean flag = sysUserRepo.importExcel(multipartFile);
        return ApiResult.result(flag);
    }

}
